package com.example.learnvien.utils;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

import com.example.learnvien.LearnViEnApplication;
import com.example.learnvien.assets.Assets;

public final class SoundUtil
{
    private static float sVolume;
    private static SoundPool sSoundPool;
    private static Map<String, Integer> sSoundMap;

    public static void init()
    {
        sSoundPool = new SoundPool(100, AudioManager.STREAM_MUSIC, 0);
        sSoundMap = new HashMap<String, Integer>();

        AudioManager audioManager = (AudioManager) LearnViEnApplication.getInstance().getSystemService(
                Context.AUDIO_SERVICE);
        float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        sVolume = actualVolume / maxVolume;
    }

    private static int addSound(String pathSound)
    {
        int id = sSoundPool.load(
                Assets.Sound.getAssetFileDescriptor(pathSound), 1);
        sSoundMap.put(pathSound, id);
        return id;
    }

    public static void play(String pathSound)
    {
        if (sSoundMap == null || sSoundPool == null)
        {
            return;
        }

        pathSound = pathSound.toLowerCase(Locale.getDefault());
        Integer soundId = sSoundMap.get(pathSound);
        if (soundId == null)
        {
            soundId = addSound(pathSound);
            try
            {
                Thread.sleep(150);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }

        if (soundId != null && soundId != 0)
        {
            sSoundPool.play(soundId, sVolume, sVolume, 1, 0, 1f);
        }
    }
}
